<template>
	<view class="p2 addgoods">
		<u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" labelWidth="85">
			<view class="bf bs5 p2">
				<u-form-item label="排序" prop="sort" borderBottom>
					<u--input v-model="form.sort" border="none" placeholder="请输入排序"></u--input>
				</u-form-item>
				<u-form-item label="商品名称" prop="name" borderBottom :required="true">
					<u--input v-model="form.name" border="none" placeholder="请输入商品名称"></u--input>
				</u-form-item>
				<u-form-item label="商品简介" prop="desc" borderBottom>
					<u-textarea v-model="form.desc" placeholder="请输入商品简介" :count="true" :maxlength="100"></u-textarea>
				</u-form-item>
				<u-form-item label="商品分类" prop="catId" borderBottom :required="true">
					<zxz-uni-data-select v-model="form.catId" :localdata="options.catLabelList" dataKey="name"
						dataValue="id" :multiple="true" placeholder="请选择商品分类"></zxz-uni-data-select>
				</u-form-item>
				<u-form-item label="商品渠道" prop="channelIds" borderBottom :required="true">
					<u-checkbox-group v-model="form.channelIds" placement="row" size="16" icon-color="#000">
						<u-checkbox :customStyle="{marginRight: '8px'}" label="外卖商品" :name="1" :activeColor="subColor">
						</u-checkbox>
						<u-checkbox :customStyle="{marginRight: '8px'}" label="店内商品" :name="2" :activeColor="subColor">
						</u-checkbox>
					</u-checkbox-group>
				</u-form-item>
				<u-form-item label="商品标签" prop="labelId" borderBottom>
					<zxz-uni-data-select v-model="form.labelId" :localdata="options.labelList" dataKey="name"
						dataValue="id" :multiple="true" placeholder="请选择商品标签"></zxz-uni-data-select>
				</u-form-item>
				<u-form-item label="商品角标" prop="markId" borderBottom>
					<uni-data-select v-model="form.markId" :localdata="options.markList"
						placeholder="请选择商品角标"></uni-data-select>
				</u-form-item>
				<u-form-item label="拼音助记码" prop="pinYin" borderBottom>
					<u--input v-model="form.pinYin" border="none" placeholder="请输入拼音助记码"></u--input>
				</u-form-item>
				<u-form-item label="初始销量" prop="initialSales" borderBottom>
					<u--input v-model="form.initialSales" border="none" placeholder="请输入初始销量"></u--input>
				</u-form-item>
				<u-form-item label="商品图片" prop="logo" borderBottom :required="true">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" uploadIcon="plus"
						name="1" :maxCount="1"></u-upload>
				</u-form-item>
				<u-form-item label="商品详情图" prop="images" borderBottom>
					<u-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" uploadIcon="plus"
						name="2" multiple :maxCount="9"></u-upload>
				</u-form-item>
				<u-form-item label="商品单位" prop="unitId" borderBottom>
					<uni-data-select v-model="form.unitId" :localdata="options.unitList"
						placeholder="请选择商品单位"></uni-data-select>
				</u-form-item>
				<u-form-item label="是否为展示商品" prop="isShow">
					<u-switch v-model="form.isShow" :inactiveValue="0" :activeValue="1" :activeColor="subColor"
						size="20">
					</u-switch>
				</u-form-item>
			</view>
			<view class="bf bs5 p2 mt10">
				<u-form-item label="商品规格" prop="specSwitch" borderBottom labelPosition="top">
					<view class="mt20">
						<view class="f-bt f-y-c">
							<u-radio-group v-model="form.specSwitch" :activeColor="subColor" placement="row" size="16"
								icon-color="#000">
								<u-radio label="单一规格" :name="0" :labelSize="14"
									:customStyle="{marginRight: '10px'}"></u-radio>
								<u-radio label="多规格" :name="1" :labelSize="14"></u-radio>
							</u-radio-group>
							<view class="f-y-c cf7c" v-if="form.specSwitch==1" @click="handGGsz">
								<text class="iconfont icon-bianji mr10 c9 f40"></text>
								<text>编辑</text>
							</view>
						</view>
						<view v-if="form.specSwitch==0" class="f-1 mt10 specd">
							<u-form-item label="销售价格" prop="price" :required="true">
								<u-input placeholder="请输入销售价格" v-model="form.singleSpec.price" type="digit"></u-input>
							</u-form-item>
							<u-form-item label="成本价" prop="costPrice">
								<u-input placeholder="请输入成本价" v-model="form.singleSpec.costPrice" type="digit"></u-input>
							</u-form-item>
							<u-form-item label="包装费" prop="boxMoney">
								<u-input placeholder="请输入包装费" v-model="form.singleSpec.boxMoney" type="digit"></u-input>
							</u-form-item>
							<u-form-item label="初始库存" prop="inventory">
								<!-- <u-number-box v-model="form.singleSpec.inventory"></u-number-box> -->
								<u-input placeholder="请输入初始库存" v-model="form.singleSpec.inventory" type="number"></u-input>
							</u-form-item>
							<u-form-item label="次日补足" prop="dayFilling">
								<u-switch v-model="form.singleSpec.dayFilling" :inactiveValue="0" :activeValue="1"
									:activeColor="subColor" size="20">
								</u-switch>
							</u-form-item>
							<view class="f-y-c">
								<u-form-item label="商品重量" prop="component">
									<u-number-box v-model="form.singleSpec.component"></u-number-box>
								</u-form-item>
								<view class="ml10">克</view>
							</view>
							<u-form-item label="商品条码" prop="barcode">
								<u--input v-model="form.singleSpec.barcode" border="none"
									placeholder="请输入商品条码"></u--input>
							</u-form-item>
							<u-form-item label="商品编码" prop="sn">
								<u--input v-model="form.singleSpec.sn" border="none" placeholder="请输入商品编码"></u--input>
							</u-form-item>

						</view>
					</view>
				</u-form-item>
				<u-form-item label="商品属性" prop="attrSwitch" borderBottom>
					<view class="f-bt f-y-c">
						<u-switch v-model="form.attrSwitch" :inactiveValue="0" :activeValue="1" :activeColor="subColor"
							size="20">
						</u-switch>
						<view class="f-y-c cf7c" v-if="form.attrSwitch==1" @click="handSXsz">
							<text class="iconfont icon-bianji mr10 c9 f40"></text>
							<text>编辑</text>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="加料商品" prop="materialSwitch">
					<view class="f-bt f-y-c">
						<u-switch v-model="form.materialSwitch" :inactiveValue="0" :activeValue="1"
							:activeColor="subColor" size="20">
						</u-switch>
						<view class="f-y-c cf7c" v-if="form.materialSwitch==1" @click="handJLsz">
							<text class="iconfont icon-bianji mr10 c9 f40"></text>
							<text>编辑</text>
						</view>
					</view>
				</u-form-item>
			</view>
			<view class="bf bs5 p2 mt10">
				<u-form-item label="参与会员折扣" prop="vipPriceSwitch" borderBottom>
					<u-switch v-model="form.vipPriceSwitch" :inactiveValue="0" :activeValue="1" :activeColor="subColor"
						size="20">
					</u-switch>
				</u-form-item>
				<u-form-item label="分时段销售" prop="salesTimeSwitch" borderBottom>
					<view class="f-bt f-y-c">
						<u-switch v-model="form.salesTimeSwitch" :inactiveValue="0" :activeValue="1"
							:activeColor="subColor" size="20">
						</u-switch>
						<view class="flex">
							<view
								v-if="form.salesTimeSwitch && form.salesTimeData.week && form.salesTimeData.week.length && form.salesTimeData.times && form.salesTimeData.times.length"
								class="f-c-e">
								<view class="flex">
									<view v-for="(v,i) in form.salesTimeData.week" :key="i">
										<text v-if="v==1" class="mr5">周一</text>
										<text v-if="v==2" class="mr5">周二</text>
										<text v-if="v==3" class="mr5">周三</text>
										<text v-if="v==4" class="mr5">周四</text>
										<text v-if="v==5" class="mr5">周五</text>
										<text v-if="v==6">周六</text>
										<text v-if="v==0" class="mr5">周日</text>
									</view>
								</view>
								<view>
									<view v-for="(v,i) in form.salesTimeData.times" :key="i">
										{{v.start}} ~ <text v-if="v.ciri">次日</text>{{v.end}}
									</view>
								</view>
							</view>
							<view class="f-y-c ml20" @click="toTime" v-if="form.salesTimeSwitch==1">
								<text>编辑</text>
								<u-icon slot="right" size="14" color="#999" name="arrow-right"></u-icon>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="售卖方式" prop="salesType" borderBottom>
					<u-radio-group v-model="form.salesType" :activeColor="subColor" placement="column" size="16"
						icon-color="#000">
						<u-radio label="可单独售卖" :name="1" :labelSize="14"
							:customStyle="{marginBottom: '10px'}"></u-radio>
						<u-radio label="仅作为赠品或套餐内的商品,不单独售卖,不单独展示给顾客" :name="0" :labelSize="14"></u-radio>
					</u-radio-group>
					<view class="mt10" v-if="form.salesType == 1">
						<u-number-box v-model="form.min"></u-number-box>
					</view>
				</u-form-item>
				<u-form-item label="限购数量" prop="orderlimitSwitch" borderBottom>
					<view>
						<view class="f-1 f-bt f-y-c">
							<view class="flex f-y-c">
								<u-switch v-model="form.orderlimitSwitch" :inactiveValue="0" :activeValue="1"
									:activeColor="subColor" size="20">
								</u-switch>
								<view class="ml10">每单限购</view>
							</view>
							<view class="flex f-y-c" v-if="form.orderlimitSwitch == 1">
								<u-number-box v-model="form.orderlimit"></u-number-box>
								<view class="ml10">份</view>
							</view>
						</view>
						<view class="f-1 f-bt f-y-c mt10">
							<view class="flex f-y-c">
								<u-switch v-model="form.userlimitSwitch" :inactiveValue="0" :activeValue="1"
									:activeColor="subColor" size="20">
								</u-switch>
								<view class="ml10">每人限购</view>
							</view>
							<view class="flex f-y-c" v-if="form.userlimitSwitch == 1">
								<u-number-box v-model="form.userlimit"></u-number-box>
								<view class="ml10">份</view>
							</view>
						</view>
						<view class="f-1 f-bt f-y-c mt10">
							<view class="flex f-y-c">
								<u-switch v-model="form.daylimitSwitch" :inactiveValue="0" :activeValue="1"
									:activeColor="subColor" size="20">
								</u-switch>
								<view class="ml10">每天限购</view>
							</view>
							<view class="flex f-y-c" v-if="form.daylimitSwitch == 1">
								<u-number-box v-model="form.daylimit"></u-number-box>
								<view class="ml10">份</view>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="单点不送" prop="oneDeliverySwitch">
					<u-switch v-model="form.oneDeliverySwitch" :inactiveValue="0" :activeValue="1"
						:activeColor="subColor" size="20">
					</u-switch>
				</u-form-item>
			</view>
			<view class="bf bs5 p2 mt10">
				<u-form-item label="商品详情" prop="content" labelPosition="top">
					<mg-editor @input='getEditor' :dval='form.content'></mg-editor>
				</u-form-item>
			</view>
		</u--form>
		<view class="buts bf5 pb10 pt10">
			<view class="p-0-20 mb10">
				<view class="c0 bs30 tac p10 wei f14" :style="{background:subColor}" @click="save">保存</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex'
	import site from '@/custom/siteroot.js';
	import config from '@/custom/config.js';
	import mgEditor from '@/components/form/mg-editor.vue'
	import {
		getPage,
	} from '@/common/handutil.js'
	export default {
		name: 'my-add-info',
		components: {
			mgEditor,
		},
		data() {
			return {
				subColor: uni.getStorageSync('subject_color'),
				form: {
					sort: '1',
					name: '',
					desc: '',
					catId: [],
					channelIds: [],
					labelId: [],
					markId: '0',
					pinYin: '',
					initialSales: '0',
					unitId: '0',
					isShow: 0,
					specSwitch: 0,
					attrSwitch: 0,
					materialSwitch: 0,
					vipPriceSwitch: 0,
					salesTimeSwitch: 0,
					salesTimeData: {
						week: [],
						times: []
					},
					salesType: 1,
					orderlimitSwitch: 0,
					userlimitSwitch: 0,
					daylimitSwitch: 0,
					orderlimit: 1,
					userlimit: 1,
					daylimit: 1,
					oneDeliverySwitch: 0,
					logo: '',
					images: [],

					singleSpec: {
						price: 0,
						linePrice: 0,
						costPrice: 0,
						boxMoney: 0,
						inventory: 999,
						dayFilling: 1,
						component: 1,
					},
					specData: [],
					attrData: [],
					materialData: [],
					skus: [],
					content: '',
					setmealData: {},
					type: 1,
					sales: 0,
					min: 1,
				},
				options: {
					catLabelList: [],
					labelList: [],
					markList: [],
					unitList: [],
				},
				fileList1: [],
				fileList2: [],
				rules: {
					name: [{
						type: 'string',
						required: true,
						message: '请输入商品名称',
						trigger: ['blur', 'change']
					}],
					catId: [{
						type: 'array',
						required: true,
						message: '请选择商品分类',
						trigger: ['blur', 'change']
					}],
					channelIds: [{
						type: 'array',
						required: true,
						message: '请选择商品渠道',
						trigger: ['blur', 'change']
					}],
					// logo: [{
					// 	type: 'string',
					// 	required: true,
					// 	message: '请上传商品图片',
					// 	trigger: ['blur', 'change']
					// }],
					// 'singleSpec.price': [{
					// 	type: 'string',
					// 	required: true,
					// 	message: '请输入销售价格',
					// 	trigger: ['blur', 'change']
					// }],
				},
				editorStr: '',
				cForm: {},
				type: '1',
			}
		},
		onLoad(options) {
			if (options && options.id) {
				this.query = options
				this.fetchData()
				this.type = options.type
			}
			this.getGoodsCatLabelList()
			this.getGoodsLabelList()
			this.getGoodsMarkList()
			this.getGoodsUnitList()
		},
		computed: {},
		methods: {
			async getGoodsCatLabelList() {
				const {
					data: {
						list
					}
				} = await this.beg.request({
					url: this.api.goodsCatList,
					data: {
						pageNo: 1,
						pageSize: 999
					}
				})
				this.options.catLabelList = list ? list : []
			},
			async getGoodsLabelList() {
				const {
					data: {
						list
					}
				} = await this.beg.request({
					url: this.api.goodsLabelList,
					data: {
						pageNo: 1,
						pageSize: 999
					}
				})
				this.options.labelList = list ? list : []
			},
			async getGoodsMarkList() {
				const {
					data: {
						list
					}
				} = await this.beg.request({
					url: this.api.goodsMarkList,
					data: {
						pageNo: 1,
						pageSize: 999
					}
				})
				this.options.markList = list.map(v => ({
					text: v.name,
					value: v.id
				}))
			},
			async getGoodsUnitList() {
				const {
					data: {
						list
					}
				} = await this.beg.request({
					url: this.api.goodsUnitList,
					data: {
						pageNo: 1,
						pageSize: 999
					}
				})
				this.options.unitList = list.map(v => ({
					text: v.name,
					value: v.id
				}))
			},
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${uni.getStorageSync('siteroot')}/channel/file/upload`,
						filePath: url,
						name: 'file',
						header: {
							contentType: config.contentType,
							appType: 'store',
							uniacid: uni.getStorageSync('uniacid'),
							storeId: uni.getStorageSync('storeId'),
							Authorization: `Bearer ${uni.getStorageSync('token')}`,
						},
						success: (res) => {
							let r = JSON.parse(res.data)
							if (r && r.code == 400) {
								uni.showToast({
									title: r.msg || r.code,
									icon: 'none',
									duration: 2000
								})
							} else {
								setTimeout(() => {
									let d = JSON.parse(res.data)
									resolve(d.data)
								}, 500)
							}
						},
						fail: (res) => {
							return uni.$u.toast(res && res.data || res)
						}
					});
				})
			},
			toTime() {
				let time = {}
				time.week = this.form.salesTimeData.week
				time.times = this.form.salesTimeData.times
				uni.navigateTo({
					url: `/pages/mine/spgl/time?form=${JSON.stringify(time)}`
				})
			},
			rfTime(v) {
				if (v) {
					this.form.salesTimeData = JSON.parse(v)
				}
			},
			getEditor(e) {
				this.editorStr = e
				this.form.content = e
			},
			async getErStr() {
				let e = this.editorStr
				if (e.indexOf('<img') > -1) {
					let arr = utils.getEditorImgs(e),
						str = e
					let parr = await uploadImg({
						files: arr
					})
					for (let i in arr) {
						str = str.replace(arr[i].imgsrcStr, arr[i].tmp ? parr[i] : parr[i])
					}
					return str.replace(/data-local(\S*)\s/g, "")
				} else {
					return e
				}
			},

			handGGsz() {
				uni.setStorageSync('fbsp-ggsz', JSON.stringify(this.form))
				uni.navigateTo({
					url: `/pages/mine/spgl/fbsp-ggsz?form=${JSON.stringify(this.form)}`
				})
			},
			editSpec(f) {
				this.form.skus = JSON.parse(JSON.stringify(f.skus))
				this.form.specData = JSON.parse(JSON.stringify(f.specData))
			},
			handSXsz() {
				uni.setStorageSync('fbsp-sxsz', JSON.stringify(this.form))
				uni.navigateTo({
					url: `/pages/mine/spgl/fbsp-sxsz?form=${JSON.stringify(this.form)}`
				})
			},
			editAttr(f) {
				this.form.attrData = JSON.parse(JSON.stringify(f.attrData))
			},
			handJLsz() {
				uni.setStorageSync('fbsp-jlsz', JSON.stringify(this.form))
				uni.navigateTo({
					url: `/pages/mine/spgl/fbsp-jlsz?form=${JSON.stringify(this.form)}`
				})
			},
			editMaterial(f) {
				this.form.materialData = JSON.parse(JSON.stringify(f.materialData))
			},

			async fetchData() {
				const {
					data
				} = await this.beg.request({
					url: `${this.api.goodsList}/${this.query.id}`,
				})
				this.cForm = JSON.parse(JSON.stringify(data))
				this.form = Object.assign(this.form, data)
				this.form.channelIds = data.channelIds ? data.channelIds : [],
					this.form.content = data.content && data.content.content ? data.content.content : '';
				if (data && data.logo) {
					this.fileList1 = []
					this.fileList1.push({
						url: data.logo
					})
				}
				if (data && data.images && data.images.length) {
					this.fileList2 = []
					data.images.forEach((v) => {
						this.fileList2.push({
							url: v
						})
					})
				}
				if (data.specSwitch == 1) {
					this.form.singleSpec = {
						price: 0,
						linePrice: 0,
						costPrice: 0,
						boxMoney: 0,
						inventory: 999,
						dayFilling: 1,
						component: 1,
					}
				} else {
					this.form.setmealData.fix[0] = this.form.setmealData.fix[0] && this.form.setmealData.fix[0].goods ?
						this.form.setmealData.fix[0] : {
							name: '固定搭配',
							type: 1,
							goods: []
						}
				}
			},
			save() {
				if (this.fileList1.length) {
					this.form.logo = ''
					this.fileList1.forEach(v => {
						this.form.logo = v.url
					})
				} else {
					return uni.$u.toast('请上传商品图片')
				}
				if (this.fileList2.length) {
					this.form.images = []
					this.fileList2.forEach(v => {
						this.form.images.push(v.url)
					})
				} else {
					this.form.images = []
				}
				console.log(123, this.fileList1, this.fileList2, this.form)
				this.$refs.uForm.validate().then(async res => {
					if (this.type && this.type == "copy") {
						this.form.id = null;
						if (this.cForm.name == this.form.name) {
							this.form.name = `${this.form.name} -复制`;
						}
					}
					if (this.form.channelIds) {
						this.form.channelIds = this.form.channelIds.sort()
					}
					const {
						msg
					} = await this.beg.request({
						url: this.form.id && this.type != 'copy' ?
							`${this.api.goodsList}/${this.form.id}` : this.api.goodsList,
						method: this.form.id && this.type != 'copy' ? 'PUT' : 'POST',
						data: this.form,
					})
					uni.$u.toast(msg)
					this.$refs.uForm.resetFields()
					this.fetchData()
					getPage().$vm.fetchData()
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 500)
				}).catch(errors => {
					console.log('errors', errors)
					uni.$u.toast('请填写必填信息')
				})
			},
		},
	}
</script>

<style scoped lang="scss">
	.addgoods {
		padding-bottom: 150rpx;
	}

	.specd {
		/deep/.u-number-box__input {
			width: 65px !important;
		}
	}

	.buts {
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 999;
	}
</style>